package cn.touna.jss.modules.third.zhima.client;

import cn.touna.jss.common.properties.disconf.ZhimaProperties;
import cn.touna.jss.modules.third.zhima.entity.ZmDataFeedbackDto;
import com.antgroup.zmxy.openplatform.api.DefaultZhimaClient;
import com.antgroup.zmxy.openplatform.api.FileItem;
import com.antgroup.zmxy.openplatform.api.ZhimaApiException;
import com.antgroup.zmxy.openplatform.api.request.ZhimaDataBatchFeedbackRequest;
import com.antgroup.zmxy.openplatform.api.response.ZhimaDataBatchFeedbackResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 芝麻信用封装的client 用于数据反馈
 * <p>
 * Created by lishuo on 2017/5/23.
 */
@Component
public class ZmDataFeedbackClient {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ZhimaProperties zhimaProperties;

    public Map<String, Object> getZmDataFeedbackResponse(ZmDataFeedbackDto zmDataFeedbackDto) throws ZhimaApiException {

        String filePath = null;
        ZhimaDataBatchFeedbackResponse response = null;

        try {
            ZhimaDataBatchFeedbackRequest req = new ZhimaDataBatchFeedbackRequest();
            req.setChannel(zmDataFeedbackDto.getChannel());
            req.setPlatform(zmDataFeedbackDto.getPlatform());
            req.setRecords(zmDataFeedbackDto.getRecords());// 必要参数
            req.setFileDescription(zmDataFeedbackDto.getDescription());
            req.setBizExtParams(zmDataFeedbackDto.getBizExtParams());

            req.setFileType(zhimaProperties.getFileType());// 必要参数
            req.setFileCharset(zhimaProperties.getCharset());// 必要参数
            req.setColumns(zhimaProperties.getColumns());// 必要参数
            req.setPrimaryKeyColumns(zhimaProperties.getPrimaryKeyColumns());// 必要参数
            req.setTypeId(zhimaProperties.getTypeId());// 必要参数

            //save data to temp data file for zhima request execution
            filePath = saveToFile(zmDataFeedbackDto.getData());
            req.setFile(new FileItem(filePath));// 必要参数

            DefaultZhimaClient client = new DefaultZhimaClient(zhimaProperties.getGatewayUrl2(), zhimaProperties.getAppId2(),
                    zhimaProperties.getPrivateKey2(), zhimaProperties.getZhimaPublicKey2());
            //send zhima request
            response = client.execute(req);
        } finally {
            //delete temp data file
            deleteFile(filePath);
        }

        //set result map
        Map<String, Object> map = new HashMap<>();
        map.put("isSuccess", response.isSuccess());

        if (response.getErrorCode() == null)
            map.put("code", "200");
        else
            map.put("code", "500");

        if (response.getErrorMessage() == null)
            map.put("message", "success");
        else
            map.put("message", response.getErrorMessage());
        return map;

    }

    private String saveToFile(String data) {

        String fileName = zhimaProperties.getFileBaseDir() + File.separator + UUID.randomUUID() + ".json";

        try {
            OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(fileName), "UTF-8");
            out.write(data.toCharArray());
            out.flush();
            out.close();
        } catch (Exception e) {
            logger.error("error write data to file", e);
            throw new RuntimeException(e);
        }

        return fileName;
    }

    private void deleteFile(String filePath) {

        try {
            // Specify the file name and path
            File file = new File(filePath);

            if (!file.delete()) {
                logger.error("Failed to delete data file");
            }
        } catch (Exception e) {
            logger.error("error: delete data file", e);
        }
    }

}
